package com.declum.archon.chunkserver.manager.disk;

import java.io.File;
import java.io.IOException;

import com.declum.archon.chunkserver.manager.IChunkMetaOperator;
import com.declum.archon.chunkserver.manager.disk.chunk.ChunkInfo;
import com.declum.archon.chunkserver.manager.disk.chunk.ChunkMetaDB;

public class DiskInfo implements IDiskOperator, IChunkMetaOperator {
	long		chunkCount;
	long		totalSpace;
	long		usedSpace;
	String		path;
	ChunkMetaDB	chunkDb;

	private DiskInfo() {
		// Avoids instantiation
	}

	public static DiskInfo getInstance(String path) throws IOException {
		DiskInfo info = new DiskInfo();
		info.setPath(path);
		return info;
	}

	public long getChunkCount() {
		return this.chunkCount;
	}

	public long getTotalSpace() {
		return this.totalSpace;
	}

	public long getUsedSpace() {
		return this.usedSpace;
	}

	public String getPath() {
		return this.path;
	}

	public void setPath(String path) throws IOException {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}

		if (!file.canRead()) {
			throw new IOException(path + " can not be modified");
		}
		if (!file.canWrite()) {
			throw new IOException(path + " can not be modified");
		}

		if (!file.isDirectory()) {
			throw new IOException(path + " must be a directory");
		}
		this.chunkDb = ChunkMetaDB.getInstance(path);
		this.path = file.getAbsolutePath();
		this.updateSpaceInfo();

	}

	public void updateSpaceInfo() {
		File file = new File(this.path);
		long totalSpace = file.getTotalSpace();
		long freeSpace = file.getFreeSpace();
		long usedSpace = totalSpace - freeSpace;
		this.totalSpace = totalSpace;
		this.usedSpace = usedSpace;

	}

	public void analysDisk(int i) {
		this.updateSpaceInfo();
	}

	public void release() {
		// TODO Auto-generated method stub
	}

	public ChunkInfo createChunk(String chunkId) throws Exception {
		ChunkInfo instance = ChunkInfo.getInstance(chunkId, this.path);
		instance.create();
		this.chunkDb.put(chunkId, instance);
		return instance;
	}

	public ChunkInfo deleteChunk(String chunkId) {
		return this.chunkDb.remove(chunkId);
	}

	@Override
	public IChunkMetaOperator getChunkMetaOperator() {
		return this;
	}

	@Override
	public synchronized ChunkInfo[] getAllChunkInfo() {
		return this.chunkDb.values().toArray(new ChunkInfo[] {});
	}
}
